/**
 * WebXR手部追踪管理器
 * 实现完整的手部追踪功能，包括手部模型创建、关节数据处理和手势识别
 */

// 导入Three.js单例，确保整个应用中只有一个Three.js实例
import { THREE, XRHandModelFactory } from '../core/three-singleton.js';

export class HandTrackingManager {
    constructor(renderer, scene, camera, options = {}) {
        this.renderer = renderer;
        this.scene = scene;
        this.camera = camera;
        
        // 配置选项
        this.options = {
            enableHandModels: true,
            enableGestureRecognition: true,
            handModelStyle: 'mesh', // 'mesh', 'boxes', 'spheres'
            debugMode: false,
            smoothingFactor: 0.8,
            gestureThreshold: 0.7,
            ...options
        };
        
        // 手部追踪状态
        this.isEnabled = false;
        this.isSupported = false;
        this.xrSession = null;
        
        // 手部模型工厂
        this.handModelFactory = new XRHandModelFactory();
        
        // 手部对象
        this.hands = {
            left: {
                controller: null,
                model: null,
                joints: new Map(),
                pose: null,
                gestures: new Map(),
                lastUpdate: 0
            },
            right: {
                controller: null,
                model: null,
                joints: new Map(),
                pose: null,
                gestures: new Map(),
                lastUpdate: 0
            }
        };
        
        // 手部关节定义（WebXR标准）
        this.jointNames = [
            'wrist',
            'thumb-metacarpal', 'thumb-phalanx-proximal', 'thumb-phalanx-distal', 'thumb-tip',
            'index-finger-metacarpal', 'index-finger-phalanx-proximal', 'index-finger-phalanx-intermediate', 'index-finger-phalanx-distal', 'index-finger-tip',
            'middle-finger-metacarpal', 'middle-finger-phalanx-proximal', 'middle-finger-phalanx-intermediate', 'middle-finger-phalanx-distal', 'middle-finger-tip',
            'ring-finger-metacarpal', 'ring-finger-phalanx-proximal', 'ring-finger-phalanx-intermediate', 'ring-finger-phalanx-distal', 'ring-finger-tip',
            'pinky-finger-metacarpal', 'pinky-finger-phalanx-proximal', 'pinky-finger-phalanx-intermediate', 'pinky-finger-phalanx-distal', 'pinky-finger-tip'
        ];
        
        // 手势识别
        this.gestureRecognizer = null;
        this.currentGestures = new Map();
        this.gestureHistory = [];
        this.gestureCallbacks = new Map();
        this.gestureRecognitionActive = false;
        
        // 性能优化
        this.updateInterval = 16; // ~60fps
        this.lastUpdateTime = 0;
        this.frameSkipCounter = 0;
        
        // 事件系统
        this.eventListeners = new Map();
        
        console.log('🤲 HandTrackingManager 初始化');
    }
    
    /**
     * 初始化手部追踪
     */
    async init() {
        try {
            // 检查WebXR支持
            await this.checkSupport();
            
            if (!this.isSupported) {
                console.warn('⚠️ 手部追踪不受支持');
                return false;
            }
            
            // 初始化手势识别器
            if (this.options.enableGestureRecognition) {
                this.initGestureRecognizer();
            }
            
            console.log('✅ HandTrackingManager 初始化完成');
            return true;
            
        } catch (error) {
            console.error('❌ HandTrackingManager 初始化失败:', error);
            return false;
        }
    }
    
    /**
     * 检查手部追踪支持
     */
    async checkSupport() {
        if (!navigator.xr) {
            this.isSupported = false;
            return false;
        }

        try {
            // 基于环境与API能力的安全检测（无需用户激活）
            const hasXRHand = 'XRHand' in window;
            const hasGetHand = !!(this.renderer && this.renderer.xr && typeof this.renderer.xr.getHand === 'function');

            // 检查VR/AR会话模式支持（Vision Pro可能为immersive-ar）
            const vrSupported = await navigator.xr.isSessionSupported('immersive-vr');
            let arSupported = false;
            if (typeof navigator.xr.isSessionSupported === 'function') {
                try {
                    arSupported = await navigator.xr.isSessionSupported('immersive-ar');
                } catch (_) {
                    arSupported = false;
                }
            }

            this.isSupported = (hasXRHand || hasGetHand) && (vrSupported || arSupported);

            console.log('🤲 手部追踪支持:', { hasXRHand, hasGetHand, vrSupported, arSupported, isSupported: this.isSupported });
            return this.isSupported;
        } catch (error) {
            console.warn('手部追踪支持检查失败:', error);
            this.isSupported = false;
            return false;
        }
    }
    
    /**
     * 启用手部追踪
     */
    async enable(xrSession) {
        console.log('🔄 开始启用手部追踪...');
        
        if (!this.isSupported) {
            console.warn('❌ 手部追踪不受支持，无法启用');
            return false;
        }
        
        try {
            this.xrSession = xrSession;
            console.log('✅ XR会话已设置:', !!this.xrSession);
            
            // 创建手部控制器
            console.log('🔄 创建手部控制器...');
            this.createHandControllers();
            
            // 创建手部模型
            if (this.options.enableHandModels) {
                console.log('🔄 创建手部模型...');
                this.createHandModels();
            } else {
                console.log('⚠️ 手部模型创建已禁用');
            }
            
            this.isEnabled = true;
            
            // 触发启用事件
            this.dispatchEvent('hand-tracking-enabled');
            
            console.log('✅ 手部追踪已启用，状态:', {
                isEnabled: this.isEnabled,
                hasLeftController: !!this.hands.left.controller,
                hasRightController: !!this.hands.right.controller,
                hasLeftModel: !!this.hands.left.model,
                hasRightModel: !!this.hands.right.model,
                enableHandModels: this.options.enableHandModels
            });
            return true;
            
        } catch (error) {
            console.error('❌ 手部追踪启用失败:', error);
            return false;
        }
    }
    
    /**
     * 禁用手部追踪
     */
    disable() {
        if (!this.isEnabled) return;
        
        // 清理手部模型
        this.cleanupHandModels();
        
        // 清理控制器
        this.cleanupControllers();
        
        this.isEnabled = false;
        this.xrSession = null;
        
        // 触发禁用事件
        this.dispatchEvent('hand-tracking-disabled');
        
        console.log('🔚 手部追踪已禁用');
    }
    
    /**
     * 创建手部控制器
     */
    createHandControllers() {
        console.log('🔄 开始创建手部控制器...');
        
        // 检查renderer.xr是否可用
        if (!this.renderer || !this.renderer.xr) {
            console.error('❌ renderer.xr 不可用');
            return;
        }
        
        console.log('✅ renderer.xr 可用，检查方法...');
        console.log('📊 renderer.xr 详细信息:', {
            hasGetHand: typeof this.renderer.xr.getHand === 'function',
            hasGetSession: typeof this.renderer.xr.getSession === 'function',
            hasGetReferenceSpace: typeof this.renderer.xr.getReferenceSpace === 'function',
            isPresenting: this.renderer.xr.isPresenting,
            session: !!this.renderer.xr.getSession()
        });
        
        if (typeof this.renderer.xr.getHand !== 'function') {
            console.error('❌ renderer.xr.getHand 方法不存在');
            return;
        }
        
        try {
            // 左手控制器
            console.log('🔄 创建左手控制器...');
            this.hands.left.controller = this.renderer.xr.getHand(0);
            
            if (this.hands.left.controller) {
                this.hands.left.controller.userData.handedness = 'left';
                this.scene.add(this.hands.left.controller);
                console.log('✅ 左手控制器已创建并添加到场景', {
                    controller: !!this.hands.left.controller,
                    hasJoints: !!this.hands.left.controller.joints,
                    jointCount: this.hands.left.controller.joints?.size || 0
                });
                
                // 添加控制器事件监听
                this.hands.left.controller.addEventListener('connected', (event) => {
                    console.log('🔗 左手控制器已连接:', {
                        handedness: event.data.handedness,
                        targetRayMode: event.data.targetRayMode,
                        hasHand: !!event.data.hand,
                        profiles: event.data.profiles
                    });
                });
                
                this.hands.left.controller.addEventListener('disconnected', () => {
                    console.log('🔌 左手控制器已断开连接');
                });
            } else {
                console.error('❌ 左手控制器创建失败');
            }
            
            // 右手控制器
            console.log('🔄 创建右手控制器...');
            this.hands.right.controller = this.renderer.xr.getHand(1);
            
            if (this.hands.right.controller) {
                this.hands.right.controller.userData.handedness = 'right';
                this.scene.add(this.hands.right.controller);
                console.log('✅ 右手控制器已创建并添加到场景', {
                    controller: !!this.hands.right.controller,
                    hasJoints: !!this.hands.right.controller.joints,
                    jointCount: this.hands.right.controller.joints?.size || 0
                });
                
                // 添加控制器事件监听
                this.hands.right.controller.addEventListener('connected', (event) => {
                    console.log('🔗 右手控制器已连接:', {
                        handedness: event.data.handedness,
                        targetRayMode: event.data.targetRayMode,
                        hasHand: !!event.data.hand,
                        profiles: event.data.profiles
                    });
                });
                
                this.hands.right.controller.addEventListener('disconnected', () => {
                    console.log('🔌 右手控制器已断开连接');
                });
            } else {
                console.error('❌ 右手控制器创建失败');
            }
            
            console.log('✅ 手部控制器创建完成');
        } catch (error) {
            console.error('❌ 创建手部控制器时发生错误:', error);
        }
    }
    
    /**
     * 创建手部模型 - 使用XRHandModelFactory
     */
    createHandModels() {
        if (!this.options.enableHandModels) {
            console.log('🚫 手部模型已禁用');
            return;
        }
        
        console.log('🎨 开始创建手部模型...');
        
        ['left', 'right'].forEach(handedness => {
            const hand = this.hands[handedness];
            
            try {
                // 使用 XRHandModelFactory 创建手部模型
                const handModel = this.handModelFactory.createHandModel(hand.controller, this.options.handModelStyle || 'mesh');
                
                if (handModel) {
                    // 配置手部模型基本属性
                    handModel.visible = true;
                    handModel.castShadow = true;
                    handModel.receiveShadow = true;
                    handModel.name = `hand-model-${handedness}`;
                    
                    // 设置模型缩放以确保可见性
                    handModel.scale.setScalar(1.2);
                    
                    // 设置材质属性
                    handModel.traverse((child) => {
                        if (child.isMesh && child.material) {
                            // 确保材质是 MeshStandardMaterial
                            if (!child.material.isMeshStandardMaterial) {
                                child.material = new THREE.MeshStandardMaterial({
                                    color: child.material.color || 0xffffff,
                                    map: child.material.map || null
                                });
                            }
                            
                            // 配置材质属性
                            child.material.roughness = 0.6;
                            child.material.metalness = 0.05;
                            child.material.transparent = false; // 不透明，更真实
                            child.material.side = THREE.DoubleSide; // 双面渲染
                            
                            // 为左右手设置不同的颜色调和发光效果
                            if (handedness === 'left') {
                                child.material.color.setHex(0xfdbcb4); // 浅肤色
                                child.material.emissive.setHex(0x002200); // 绿色发光
                                child.material.emissiveIntensity = 0.3; // 增强发光强度
                            } else {
                                child.material.color.setHex(0xf4a582); // 稍深肤色
                                child.material.emissive.setHex(0x000022); // 蓝色发光
                                child.material.emissiveIntensity = 0.3; // 增强发光强度
                            }
                            
                            // 启用阴影
                            child.castShadow = true;
                            child.receiveShadow = true;
                            
                            // 强制更新材质
                            child.material.needsUpdate = true;
                        }
                    });
                    
                    // 存储模型引用
                    hand.model = handModel;
                    
                    // 添加到控制器
                    hand.controller.add(handModel);
                    
                    // 确保控制器添加到场景
                    if (!hand.controller.parent) {
                        this.scene.add(hand.controller);
                    }
                    
                    console.log(`✅ ${handedness}手XR模型创建成功:`, {
                        hasModel: !!hand.model,
                        visible: hand.model.visible,
                        children: hand.model.children.length,
                        inController: hand.model.parent === hand.controller,
                        controllerInScene: !!hand.controller.parent
                    });
                } else {
                    console.warn(`⚠️ ${handedness}手XR模型创建失败，使用备用模型`);
                    this.createFallbackHandModel(handedness);
                }
            } catch (error) {
                console.error(`❌ ${handedness}手XR模型创建失败:`, error);
                console.log(`🔄 为${handedness}手创建备用模型...`);
                this.createFallbackHandModel(handedness);
            }
        });
        
        // 添加调试可视化（如果启用调试模式）
        if (this.options.debugMode) {
            this.addDebugVisualization();
        }
        
        console.log('✅ 手部模型创建完成');
    }
    
    /**
     * 创建备用手部模型（简单几何体）
     */
    createFallbackHandModels() {
        console.log('🔄 创建备用手部模型...');
        this.createFallbackHandModel('left');
        this.createFallbackHandModel('right');
    }
    
    /**
     * 创建单个备用手部模型 - 符合WebXR官方API
     */
    createFallbackHandModel(handedness) {
        console.log(`🔄 创建${handedness}手备用模型...`);
        
        try {
            const hand = this.hands[handedness];
            
            // 创建手部模型组
            const handGroup = new THREE.Group();
            handGroup.name = `fallback-hand-${handedness}`;
            
            // 手掌球体（主要部分）- 更大更明显
            const palmGeometry = new THREE.SphereGeometry(0.06, 16, 12);
            const palmMaterial = new THREE.MeshStandardMaterial({
                color: handedness === 'left' ? 0x00ff00 : 0x0000ff,
                transparent: false, // 不透明，更容易看见
                emissive: handedness === 'left' ? 0x004400 : 0x000044,
                emissiveIntensity: 0.5,
                roughness: 0.3,
                metalness: 0.2
            });
            
            const palmMesh = new THREE.Mesh(palmGeometry, palmMaterial);
            palmMesh.name = 'palm';
            palmMesh.castShadow = true;
            palmMesh.receiveShadow = true;
            handGroup.add(palmMesh);
            
            // 创建5个手指球体 - 更大更明显
            const fingerPositions = [
                { name: 'thumb', offset: new THREE.Vector3(0.04, 0.03, 0.03) },
                { name: 'index', offset: new THREE.Vector3(0.03, 0.07, 0.02) },
                { name: 'middle', offset: new THREE.Vector3(0, 0.08, 0) },
                { name: 'ring', offset: new THREE.Vector3(-0.03, 0.07, 0.02) },
                { name: 'pinky', offset: new THREE.Vector3(-0.04, 0.06, 0.03) }
            ];
            
            fingerPositions.forEach(finger => {
                const fingerGeometry = new THREE.SphereGeometry(0.02, 8, 6);
                const fingerMaterial = new THREE.MeshStandardMaterial({
                    color: handedness === 'left' ? 0x00cc00 : 0x0000cc,
                    transparent: false,
                    emissive: handedness === 'left' ? 0x002200 : 0x000022,
                    emissiveIntensity: 0.3,
                    roughness: 0.4,
                    metalness: 0.1
                });
                
                const fingerMesh = new THREE.Mesh(fingerGeometry, fingerMaterial);
                fingerMesh.name = finger.name;
                fingerMesh.position.copy(finger.offset);
                fingerMesh.castShadow = true;
                fingerMesh.receiveShadow = true;
                handGroup.add(fingerMesh);
            });
            
            // 设置整体缩放 - 更大以便观察
            handGroup.scale.setScalar(1.5);
            
            // 设置初始位置 - 在用户前方可见位置
            handGroup.position.set(
                handedness === 'left' ? -0.3 : 0.3, // 左右分开
                1.2, // 胸部高度
                -0.5 // 用户前方
            );
            
            // 确保模型可见
            handGroup.visible = true;
            
            // 存储模型引用
            hand.model = handGroup;
            
            // 直接添加到场景，确保可见
            this.scene.add(handGroup);
            
            console.log(`✅ ${handedness}手备用模型创建完成并添加到场景:`, {
                name: handGroup.name,
                position: handGroup.position,
                scale: handGroup.scale,
                visible: handGroup.visible,
                children: handGroup.children.length
            });
            
        } catch (error) {
            console.error(`❌ ${handedness}手备用模型创建失败:`, error);
        }
    }
    
    /**
     * 添加调试可视化
     */
    addDebugVisualization() {
        console.log('🔄 添加调试可视化...');
        
        ['left', 'right'].forEach(handedness => {
            const controller = this.hands[handedness].controller;
            if (controller) {
                // 添加坐标轴辅助器
                const axesHelper = new THREE.AxesHelper(0.1);
                controller.add(axesHelper);
                
                // 添加线框球体
                const wireframeGeometry = new THREE.SphereGeometry(0.08, 8, 8);
                const wireframeMaterial = new THREE.MeshBasicMaterial({ 
                    color: handedness === 'left' ? 0x00ff00 : 0x0000ff,
                    wireframe: true 
                });
                const wireframeMesh = new THREE.Mesh(wireframeGeometry, wireframeMaterial);
                controller.add(wireframeMesh);
            }
        });
    }
    
    /**
     * 设置手部模型材质
     */
    setupHandMaterials() {
        const handMaterial = new THREE.MeshStandardMaterial({
            color: 0xfdbcb4, // 肤色
            roughness: 0.8,
            metalness: 0.0,
            transparent: true,
            opacity: 0.9
        });
        
        // 应用材质到手部模型
        ['left', 'right'].forEach(handedness => {
            const model = this.hands[handedness].model;
            if (model) {
                model.traverse((child) => {
                    if (child.isMesh) {
                        child.material = handMaterial.clone();
                        child.castShadow = true;
                        child.receiveShadow = true;
                    }
                });
            }
        });
    }
    
    /**
     * 更新手部追踪数据
     */
    update(frame, delta) {
        if (!this.isEnabled || !frame || !this.xrSession) return;
        
        const currentTime = performance.now();
        
        // 性能优化：限制更新频率
        if (currentTime - this.lastUpdateTime < this.updateInterval) {
            return;
        }
        
        this.lastUpdateTime = currentTime;
        
        // 更新手部数据
        this.updateHandData(frame);
        
        // 更新手势识别
        if (this.options.enableGestureRecognition) {
            this.updateGestureRecognition();
        }
        
        // 触发更新事件
        this.dispatchEvent('hand-tracking-updated', {
            leftHand: this.hands.left,
            rightHand: this.hands.right,
            timestamp: currentTime
        });
    }
    
    /**
     * 更新手部数据 - 根据官方WebXR Hand Tracking API
     */
    updateHandData(frame) {
        if (!frame || !this.xrSession) return;
        
        // 每60帧输出一次调试信息
        if (this.frameSkipCounter % 60 === 0) {
            console.log('🔄 更新手部数据 (官方API)...', {
                frame: !!frame,
                session: !!this.xrSession,
                inputSourcesLength: this.xrSession.inputSources?.length || 0
            });
        }
        
        // 遍历所有输入源，查找手部追踪输入源
        for (const inputSource of this.xrSession.inputSources) {
            // 检查是否是手部追踪输入源
            if (inputSource.hand && (inputSource.handedness === 'left' || inputSource.handedness === 'right')) {
                const handedness = inputSource.handedness;
                const hand = this.hands[handedness];
                const xrHand = inputSource.hand; // XRHand对象
                
                try {
                    // 清空之前的关节数据
                    hand.joints.clear();
                    
                    // 遍历所有手部关节
                    for (const jointName of this.jointNames) {
                        // 获取关节空间 (XRJointSpace)
                        const jointSpace = xrHand.get(jointName);
                        
                        if (jointSpace) {
                            try {
                                // 获取关节姿态 (XRJointPose)
                                const jointPose = frame.getJointPose(jointSpace, this.renderer.xr.getReferenceSpace());
                                
                                if (jointPose) {
                                    // 存储关节数据
                                    hand.joints.set(jointName, {
                                        position: new THREE.Vector3().copy(jointPose.transform.position),
                                        quaternion: new THREE.Quaternion().copy(jointPose.transform.orientation),
                                        radius: jointPose.radius || 0.01,
                                        transform: jointPose.transform,
                                        space: jointSpace
                                    });
                                }
                            } catch (jointError) {
                                // 某些关节可能无法获取，这是正常的
                                if (this.frameSkipCounter % 300 === 0) { // 减少错误日志频率
                                    console.debug(`⚠️ 无法获取${handedness}手${jointName}关节:`, jointError.message);
                                }
                            }
                        }
                    }
                    
                    // 如果成功获取到关节数据，更新手部姿态
                    if (hand.joints.size > 0) {
                        this.updateHandPose(handedness, frame);
                        hand.lastUpdate = performance.now();
                        
                        // 确保手部模型可见
                        if (hand.model) {
                            hand.model.visible = true;
                        }
                        
                        // 每60帧输出一次成功状态
                        if (this.frameSkipCounter % 60 === 0) {
                            console.log(`✅ ${handedness}手追踪成功，关节数量: ${hand.joints.size}`);
                        }
                    }
                    
                } catch (error) {
                    if (this.frameSkipCounter % 60 === 0) {
                        console.warn(`❌ ${handedness}手数据处理失败:`, error);
                    }
                }
            }
        }
        
        this.frameSkipCounter++;
    }
    
    /**
     * 更新关节数据
     */

    
    /**
     * 更新手部姿势 - 支持XRHandModelFactory模型
     */
    updateHandPose(handedness, frame) {
        const hand = this.hands[handedness];
        
        // 计算手部整体姿势
        const wristJoint = hand.joints.get('wrist');
        if (wristJoint) {
            hand.pose = {
                position: wristJoint.position.clone(),
                quaternion: wristJoint.quaternion.clone(),
                timestamp: performance.now()
            };
            
            // 更新手部模型位置（如果存在）
            if (hand.model && hand.controller) {
                // 对于XRHandModelFactory创建的模型，通常会自动跟随控制器
                // 但我们需要确保控制器位置正确
                if (hand.controller.matrixAutoUpdate !== false) {
                    // 更新控制器的位置和旋转
                    hand.controller.position.copy(wristJoint.position);
                    hand.controller.quaternion.copy(wristJoint.quaternion);
                    hand.controller.updateMatrix();
                }
                
                // 确保模型和控制器都可见
                hand.model.visible = true;
                hand.controller.visible = true;
                
                // 每60帧输出一次位置更新信息
                if (this.frameSkipCounter % 60 === 0) {
                    console.log(`🔄 ${handedness}手XR模型位置更新:`, {
                        wrist: wristJoint.position,
                        controllerPos: hand.controller.position,
                        modelVisible: hand.model.visible,
                        controllerVisible: hand.controller.visible,
                        modelInController: hand.model.parent === hand.controller
                    });
                }
            } else if (hand.model && !hand.controller) {
                // 如果是备用模型（直接在场景中）
                hand.model.position.copy(wristJoint.position);
                hand.model.quaternion.copy(wristJoint.quaternion);
                hand.model.visible = true;
                
                if (this.frameSkipCounter % 60 === 0) {
                    console.log(`🔄 ${handedness}手备用模型位置更新:`, {
                        wrist: wristJoint.position,
                        modelPos: hand.model.position,
                        modelVisible: hand.model.visible
                    });
                }
            }
        }
    }
    
    /**
     * 初始化手势识别器
     */
    initGestureRecognizer() {
        this.gestureRecognizer = {
            // 基础手势识别函数
            recognizePointing: this.recognizePointingGesture.bind(this),
            recognizePinch: this.recognizePinchGesture.bind(this),
            recognizeFist: this.recognizeFistGesture.bind(this),
            recognizeOpenHand: this.recognizeOpenHandGesture.bind(this),
            recognizeThumbsUp: this.recognizeThumbsUpGesture.bind(this)
        };
        // 默认不激活，等待显式start
        this.gestureRecognitionActive = false;
        console.log('👆 手势识别器已初始化');
    }
    
    /**
     * 更新手势识别
     */
    updateGestureRecognition() {
        if (!this.gestureRecognizer || !this.gestureRecognitionActive) return;
        
        ['left', 'right'].forEach(handedness => {
            const hand = this.hands[handedness];
            if (hand.joints.size === 0) return;
            
            // 识别各种手势
            const gestures = {
                pointing: this.gestureRecognizer.recognizePointing(hand),
                pinch: this.gestureRecognizer.recognizePinch(hand),
                fist: this.gestureRecognizer.recognizeFist(hand),
                openHand: this.gestureRecognizer.recognizeOpenHand(hand),
                thumbsUp: this.gestureRecognizer.recognizeThumbsUp(hand)
            };
            
            // 更新手势状态
            this.updateGestureState(handedness, gestures);
        });
    }

    /**
     * 启动手势识别
     */
    startGestureRecognition() {
        if (!this.gestureRecognizer) {
            this.initGestureRecognizer();
        }
        this.gestureRecognitionActive = true;
        console.log('🎯 HandTrackingManager 手势识别已启动');
    }

    /**
     * 停止手势识别
     */
    stopGestureRecognition() {
        this.gestureRecognitionActive = false;
        console.log('🛑 HandTrackingManager 手势识别已停止');
    }
    
    /**
     * 识别指向手势
     */
    recognizePointingGesture(hand) {
        const indexTip = hand.joints.get('index-finger-tip');
        const indexProximal = hand.joints.get('index-finger-phalanx-proximal');
        const middleTip = hand.joints.get('middle-finger-tip');
        const wrist = hand.joints.get('wrist');
        
        if (!indexTip || !indexProximal || !middleTip || !wrist) return 0;
        
        // 检查食指是否伸直
        const indexDirection = new THREE.Vector3().subVectors(indexTip.position, indexProximal.position).normalize();
        const wristToIndex = new THREE.Vector3().subVectors(indexTip.position, wrist.position).normalize();
        
        const indexStraightness = indexDirection.dot(wristToIndex);
        
        // 检查其他手指是否弯曲
        const wristToMiddle = new THREE.Vector3().subVectors(middleTip.position, wrist.position);
        const wristToIndexLength = wrist.position.distanceTo(indexTip.position);
        const wristToMiddleLength = wristToMiddle.length();
        
        const fingersCurled = wristToMiddleLength < wristToIndexLength * 0.8 ? 1 : 0;
        
        return Math.max(0, Math.min(1, indexStraightness * 0.7 + fingersCurled * 0.3));
    }
    
    /**
     * 识别捏合手势
     */
    recognizePinchGesture(hand) {
        const thumbTip = hand.joints.get('thumb-tip');
        const indexTip = hand.joints.get('index-finger-tip');
        
        if (!thumbTip || !indexTip) return 0;
        
        const distance = thumbTip.position.distanceTo(indexTip.position);
        const pinchThreshold = 0.03; // 3cm
        
        return Math.max(0, 1 - (distance / pinchThreshold));
    }
    
    /**
     * 识别拳头手势
     */
    recognizeFistGesture(hand) {
        const wrist = hand.joints.get('wrist');
        const fingerTips = [
            'thumb-tip', 'index-finger-tip', 'middle-finger-tip', 
            'ring-finger-tip', 'pinky-finger-tip'
        ];
        
        if (!wrist) return 0;
        
        let closedFingers = 0;
        let validFingers = 0;
        
        fingerTips.forEach(tipName => {
            const tip = hand.joints.get(tipName);
            if (tip) {
                const distance = wrist.position.distanceTo(tip.position);
                if (distance < 0.12) { // 12cm threshold for closed fist
                    closedFingers++;
                }
                validFingers++;
            }
        });
        
        return validFingers > 0 ? closedFingers / validFingers : 0;
    }
    
    /**
     * 识别张开手掌手势
     */
    recognizeOpenHandGesture(hand) {
        return 1 - this.recognizeFistGesture(hand);
    }
    
    /**
     * 识别竖拇指手势
     */
    recognizeThumbsUpGesture(hand) {
        const thumbTip = hand.joints.get('thumb-tip');
        const wrist = hand.joints.get('wrist');
        const indexTip = hand.joints.get('index-finger-tip');
        
        if (!thumbTip || !wrist || !indexTip) return 0;
        
        // 检查拇指是否向上
        const thumbDirection = new THREE.Vector3().subVectors(thumbTip.position, wrist.position);
        const upVector = new THREE.Vector3(0, 1, 0);
        const thumbUpness = thumbDirection.normalize().dot(upVector);
        
        // 检查其他手指是否弯曲
        const fistness = this.recognizeFistGesture(hand);
        
        return Math.max(0, thumbUpness * 0.6 + fistness * 0.4);
    }
    
    /**
     * 更新手势状态
     */
    updateGestureState(handedness, gestures) {
        const hand = this.hands[handedness];
        const prevGestures = hand.gestures;
        
        Object.entries(gestures).forEach(([gestureName, confidence]) => {
            const prevConfidence = prevGestures.get(gestureName) || 0;
            
            // 手势开始
            if (confidence > this.options.gestureThreshold && prevConfidence <= this.options.gestureThreshold) {
                this.dispatchEvent('gesture-start', {
                    handedness,
                    gesture: gestureName,
                    confidence
                });
            }
            
            // 手势结束
            if (confidence <= this.options.gestureThreshold && prevConfidence > this.options.gestureThreshold) {
                this.dispatchEvent('gesture-end', {
                    handedness,
                    gesture: gestureName,
                    confidence: prevConfidence
                });
            }
            
            hand.gestures.set(gestureName, confidence);
        });
    }
    
    /**
     * 获取手部数据
     */
    getHandData(handedness) {
        return this.hands[handedness] || null;
    }
    
    /**
     * 获取关节位置
     */
    getJointPosition(handedness, jointName) {
        const hand = this.hands[handedness];
        if (!hand || !hand.joints.has(jointName)) return null;
        
        return hand.joints.get(jointName).position.clone();
    }
    
    /**
     * 获取当前手势
     */
    getCurrentGestures(handedness) {
        const hand = this.hands[handedness];
        if (!hand) return new Map();
        
        return new Map(hand.gestures);
    }
    
    /**
     * 清理手部模型
     */
    cleanupHandModels() {
        ['left', 'right'].forEach(handedness => {
            const hand = this.hands[handedness];
            if (hand.model && hand.model.parent) {
                hand.model.parent.remove(hand.model);
            }
            hand.model = null;
            hand.joints.clear();
            hand.gestures.clear();
        });
    }
    
    /**
     * 清理控制器
     */
    cleanupControllers() {
        ['left', 'right'].forEach(handedness => {
            const hand = this.hands[handedness];
            if (hand.controller && hand.controller.parent) {
                hand.controller.parent.remove(hand.controller);
            }
            hand.controller = null;
        });
    }
    
    /**
     * 事件系统
     */
    addEventListener(eventType, callback) {
        if (!this.eventListeners.has(eventType)) {
            this.eventListeners.set(eventType, []);
        }
        this.eventListeners.get(eventType).push(callback);
    }
    
    removeEventListener(eventType, callback) {
        if (this.eventListeners.has(eventType)) {
            const listeners = this.eventListeners.get(eventType);
            const index = listeners.indexOf(callback);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }
    
    dispatchEvent(eventType, data = {}) {
        if (this.eventListeners.has(eventType)) {
            this.eventListeners.get(eventType).forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`事件处理错误 (${eventType}):`, error);
                }
            });
        }
    }
    
    /**
     * 销毁管理器
     */
    dispose() {
        this.disable();
        this.eventListeners.clear();
        this.gestureRecognizer = null;
        
        console.log('🗑️ HandTrackingManager 已销毁');
    }
}